<?php
namespace Framework\SlickGrid;

class SlickGrid implements \Framework\PageComponent, \Framework\ClientWidget {
	
	private static $ids = array();
	private $id = null;
	private $dataProvider = null;
	private $columns = null;
	private $options = null;
	
	// PageComponent implementation
	public function getJSIncludes() {
		return array(
			'/js/vendor/slickgrid/lib/jquery-1.4.3.min.js', 
			'/js/vendor/slickgrid/lib/jquery.event.drag-2.0.min.js', 
			'/js/vendor/slickgrid/dist/slick.grid-1.4.3.min.js',
			'/js/vendor/slickgrid/lib/jquery-ui-1.8.5.custom.min.js'
		);
	}

	// PageComponent implementation
	public function render() {
		$buffer = "<div id=\"$this->id\" class=\"grid\"></div>";
		
		return $buffer;
	}
	
	public function getScript() {
		$buffer = '
		<script>

		var grid;
		var columns = ';
		
		$buffer .= $this->columns->render();
		$buffer .= ';
		var options = ';
		$buffer .= json_encode($this->options);
		
		$buffer .= '
		$(function() {
            var data = ';
		$buffer .= $this->dataProvider->render();
		$buffer .= ';';
		$buffer .= '
			grid = new Slick.Grid($("#'.$this->id.'"), data, columns, options);
		})

		</script>';
		return $buffer;
	}
	
	public function getStylesheets() {
		return array(
			'../../../css/grid.css', 
			'../../../js/vendor/slickgrid/slick.grid.css', 
			'../../../js/vendor/slickgrid/css/smoothness/jquery-ui-1.8.5.custom.css', 
			'../../../js/vendor/slickgrid/examples/examples.css'
		);
	}
	
	public function __construct($id) {
		if(array_key_exists($id, self::$ids)) {
			throw new Exception("Duplicate ID used. IDs must be unique");
		} else {
			$this->id = $id;
			self::$ids[$id] = $this;
		}
	}
	
	public function setData(GridDataProvider $dataProvider) {
		$this->dataProvider = $dataProvider;
		$this->columns = $dataProvider->getColumns();
	}
	
	public function setColumns(ColumnCollection $columns) {
		$this->columns = $columns;
	}
	
	public function setOptions($options) {
		$this->options = $options;
	}
	
	public function getWidgetType() {
		return 'grid';
	}
	
	public function getWidgetData() {
		return array(
			'columns' => $this->columns->render(true), 
			'options' => $this->options,
			'data' => $this->dataProvider->render(true),
			'id' => $this->id
		);
	}
	
}